<?php


namespace Melon\Foundation;


class Request
{
    /**
     * 获取请求方式
     * @var string
     */
    protected string $method = '';

    /**
     * @var string
     */
    protected string $uri = '';

    /**
     * @var string 协议
     */
    protected string $protocol = '';

    /**
     * @var array 头部
     */
    protected array $header = [];

    /**
     * Cookie 管理器
     * @var array
     */
    protected array $cookie;

    /**
     * 格式化
     * @param resource $conn
     * @param string $remote_address
     */
    public function parse($conn, string $remote_address) {
        $first_line = stream_get_line($conn, 1024, "\r\n");
        [$this->method, $this->uri, $this->protocol] = explode(" ", $first_line);

        // 获取远程地址
        [$this->header['REMOTE_HOST'], $this->header['REMOTE_PORT']] = explode(":", $remote_address);

        // 获取 header
        while ($header = stream_get_line($conn, 1024, "\r\n")) {
            [$key, $value] = explode(": ", $header);

            if ($key == 'Cookie') {
                $this->cookie = array_column(array_map(function ($item) {
                    return explode("=", $item);
                }, explode("; ", $value)), 1, 0);
            } else {
                $this->header[$key] = $value;
            }
        }
    }

    /**
     * 获取单个cookie
     * @param string $key
     * @return null | string
     */
    public function cookie(string $key) :?string {
        return $this->cookie[$key] ?? null;
    }

    /**
     * 获取全部cookie
     * @return array
     */
    public function cookies() :array {
        return $this->cookie;
    }

    /**
     * 获取请求方式
     * @return string
     */
    public function method() :string {
        return $this->method;
    }

    public function uri() :string {
        return $this->uri;
    }
}
